from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, HttpResponse
import re

"""
中间件，过滤权限
"""
from django.conf import settings


class CheckPermissions(MiddlewareMixin):

    def process_request(self, request):
        # 验证访问url白名单
        valid_url = settings.VALID_URL
        # 获取 当前访问的url
        current_url = request.path_info
        # 判断当前访问你的url是否在白名单中
        for url in valid_url:
            if re.match(url, current_url):
                return None
        # 判断用户是否登录
        current_user = request.session.get('current_user')
        if not current_user:
            return redirect('/login/')
        # 获取当前访问用户拥有的权限列表
        permissions_dic = request.session.get(settings.PERMISSION_SESSION_KEY)
        # 判断当前访问的url是否在当前用的所拥有的权限列表中
        url_record = [{'title': '首页', 'url': '/customer/list/'}]  # 设置菜单路径导航显示信息
        flag = False
        for item in permissions_dic.values():
            ex = "^/web%s$" % item['url']
            ex2 = "^%s$" % item['url']
            if re.match(ex, current_url) or re.match(ex2, current_url):
                flag = True
                if not item['pid']:  # 如果访问的权限url没有pid，则表示一级菜单
                    url_record.extend([{'title': item['title'], 'url': item['url']}])
                else:
                    url_record.extend([{'title': item['p_title'], 'url': item['p_url']},
                                       {'title': item['title'], 'url': item['url']}]
                                      )
                request.url_record = url_record  # 存入全局的request 供调用
                break
        if not flag:
            return HttpResponse('PERMISSION ERROR:无权限访问，请联系管理员配置权限')
